﻿using System.Text;
using System.Windows.Forms;

namespace gisgeb.plugins.newsolution
{
    using System.IO;

    internal class NewSolutionCreator
    {
        private readonly string versionAsNumeric;

        private readonly string versionAsYear;

        internal NewSolutionCreator(string versionAsNumeric, string versionAsYear)
        {
            this.versionAsNumeric = versionAsNumeric;
            this.versionAsYear = versionAsYear;
        }

        internal void CreateComponentAt(string dicionary)
        {
            ComponentenNameDialog dlg = new ComponentenNameDialog();
            if (dlg.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            this.CreateFolder(dicionary, dlg.ComponentName);
            this.CreateSolution(dicionary, dlg.ComponentName);
        }

        private void CreateSolution(string dicionary, string componentName)
        {
            string componentFolder = GetSubfolderName(dicionary, componentName);
            string solutionFile = Path.Combine(componentFolder, string.Format("{0}.sln", componentName));
            using (StreamWriter sw = new StreamWriter(File.Open(solutionFile, FileMode.Create), new UTF8Encoding(true)))
            {
                sw.WriteLine();
                sw.WriteLine(string.Format("Microsoft Visual Studio Solution File, Format Version {0}", this.versionAsNumeric));
                sw.WriteLine(string.Format("# Visual Studio {0}", this.versionAsYear));
                sw.WriteLine("Global");

                sw.WriteLine("\tGlobalSection(SolutionConfigurationPlatforms) = preSolution");
                sw.WriteLine("\t\tDebug|Any CPU = Debug|Any CPU");
                sw.WriteLine("\t\tRelease|Any CPU = Release|Any CPU");
                sw.WriteLine("\tEndGlobalSection");

                sw.WriteLine("\tGlobalSection(SolutionProperties) = preSolution");
                sw.WriteLine("\t\tHideSolutionNode = FALSE");
                sw.WriteLine("\tEndGlobalSection");
                
                sw.WriteLine("EndGlobal");
            }

        }

        private void CreateFolder(string dicionary, string componentName)
        {
            string newFolder = GetSubfolderName(dicionary, componentName);
            Directory.CreateDirectory(newFolder);
        }

        private string GetSubfolderName(string dicionary, string componentName)
        {
            return Path.Combine(dicionary, componentName);
        }
    }
}
